package session1.examples;

import java.io.PrintStream;
import java.util.Scanner;

public class Eg1 {
	static Thread pt,ct;
	public
	static PrintStream[] printStream;
	static void dualPrint(String string){
		for(PrintStream p:printStream)
			if(p!=null)	p.print(string);
	}
	public static void main(String[] args) {
		printStream=new PrintStream[2];
		printStream[0]= System.out;
		try{
			printStream[1] = new PrintStream("out.txt");
		}
		catch (Exception e){
			System.out.println(e.getMessage());
			System.exit(0);
		}
		Data s=new Data();
		pt=new Producer(s);
		ct=new Consumer(s);
		pt.start();
		ct.start();
		new Scanner(System.in).nextLine();
		System.exit(0);
	}
}
class Data{
	private int d;
	public int getD() {
		return d;
	}
	void produce(int d){
		Eg1.dualPrint(d+" produced ");
		this.d+=d;
		show();
	}
	void show(){
		Eg1.dualPrint(d+" left\n");
	}
	void consume(int d){
		Eg1.dualPrint(d+" consumed ");
		this.d-=d;
		show();
	}
}
class Producer extends Thread{
	private final int MAX=500;
	private final Data data;
	Producer(Data data){
		this.data=data;
	}
	@Override
	public void run() {
		while (true)	synchronized (data){
			if(data.getD()<MAX){
				try {Thread.sleep(1000);}
				catch (InterruptedException interruptedException) {
					System.out.println(interruptedException.getMessage());
				}
				data.produce(100);
				data.notify();
			}
			else{
				Eg1.dualPrint("Producer: Too much produced");
				try {
					System.out.print("\t");
					System.out.println("\t");
					data.wait();
				}
				catch 	(InterruptedException e) {	e.printStackTrace();	}
			}
		}
	}
}
class Consumer extends Thread{
	private final Data data;
	static int amount=0;
	Consumer(Data data){
		this.data=data;
	}
	@Override
	public void run() {
		while (true)	synchronized (data){
			int MAX = 100;
			if(data.getD()>=(amount=(int)
					(Math.random()* MAX)
			))
			//	synchronized (data)
			{
				data.consume(amount);
				data.notifyAll();/*signal(data)*/
				try {	Thread.sleep(200);	}
				catch 	(Exception e){	System.out.println(e.getMessage());	}
			}
			else
			//	synchronized (data)
			{
				Eg1.dualPrint("Consumer:"+
						"Insufficient Storage for need "+amount+"\n");
				try {	data.wait();}
				catch 	(InterruptedException e) {
						System.out.println(e.getMessage());
				}
			}
		}
	}
}